#include "FingerPrint-manager.h"
#include <functional>
#include <mutex>
#include <unistd.h>

FingerPrintManager::FingerPrintManager(FingerPrintDevice *fingerPrintDevice)
{
	this->verifyThreadPauseFlag = false;
	this->fingerPrintDevice     = fingerPrintDevice;
	this->verifyLoopThread =
	    new thread(std::bind(&FingerPrintManager::verifyFingerprintTaskRun, this));
}

void FingerPrintManager::verifyFingerprintTaskRun(void)
{
	while(1)
	{
		cout << "verify fingerprint task run" << endl;
		while(verifyThreadPauseFlag)
		{
			// 条件变量
			unique_lock<std::mutex> lock(verifyMutex);
			verifyCond.wait(lock);
		}

#if 0  
		//小车上使用
        bool touchState = fingerPrintDevice->isTouchState();
        if (touchState) {
            uint16_t pos;
            bool     ok = fingerPrintDevice->verfiyFingerPrint(pos);
            cout << "verfiy fingerprint ok:" << ok << ",pos" << pos << endl;
        }
        else {
            sleep(1);
            continue;
        }
#else
		//pc上使用
		uint16_t pos;
		bool     ok = fingerPrintDevice->verfiyFingerPrint(pos);
		cout << "verfiy fingerprint ok:" << ok << ",pos" << pos << endl;
		sleep(1);
#endif
	}
}

void FingerPrintManager::pauseVerifyFingerprintTaks(void)
{
	verifyThreadPauseFlag = true;
	// 等待锁
	unique_lock<std::mutex> lock(verifyMutex);
}

void FingerPrintManager::resumeVerifyFingerprintTaks(void)
{
	verifyThreadPauseFlag = false;
	// notify 唤醒锁
	verifyMutex.lock();
	verifyCond.notify_one();
	verifyMutex.unlock();
}
/**
 * 记录指纹
 */
bool FingerPrintManager::recordFingerprint(uint16_t pos)
{
	// 暂停比对
	pauseVerifyFingerprintTaks();

	bool touchState = false;
#if 0
	//小厂上使用
	for(int i = 0; i < 5; i++)
	{
		touchState = fingerPrintDevice->isTouchState();
		if(touchState)
		{
			break;
		}
		sleep(1);
	}


	bool ok;
	if(touchState)
	{
		ok = fingerPrintDevice->recordFingerprint(pos);
	}
#else
	//pc上使用
	bool ok = fingerPrintDevice->recordFingerprint(pos);
#endif

	// 开启比对
	resumeVerifyFingerprintTaks();
	return ok;
}

bool FingerPrintManager::deleteFingerprint(const uint16_t pos)
{
	// 暂停比对
	pauseVerifyFingerprintTaks();
	bool ok = fingerPrintDevice->deleteFingerprint(pos);
	// 开启比对
	resumeVerifyFingerprintTaks();

	return ok;
}

bool FingerPrintManager::clearFingerprintLib(void)
{
	// 暂停比对
	pauseVerifyFingerprintTaks();
	bool ok = fingerPrintDevice->clearFingerprintLib();
	// 开启比对
	resumeVerifyFingerprintTaks();
	return ok;
}
